package com.gupao.proxydemo.custom;

import lombok.Data;

import java.io.*;

@Data
public class GPClassLoader extends ClassLoader {

    private File classPath;

    public GPClassLoader() {
        String filePath = GPClassLoader.class.getResource("").getPath();
        this.classPath = new File(filePath);

    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = GPClassLoader.class.getPackage().getName() + "." + name;
        if (classPath != null) {
            File classFile = new File(classPath, name.replaceAll("\\.", "/") + ".class");
            FileInputStream fis = null;
            ByteArrayOutputStream bos = null;
            try {
                fis = new FileInputStream(classFile);
                bos = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len = fis.read(bytes)) != -1) {
                    bos.write(bytes, 0, len);
                }
                return defineClass(className, bos.toByteArray(), 0, bos.size());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
